package com.example.roleplay.controller;

import com.example.roleplay.service.AIEnhancementService;
import com.example.roleplay.service.WebSearchService;
import com.example.roleplay.service.WebSearchService.SearchResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索功能控制器
 * 提供网络搜索和AI增强搜索功能
 */
@RestController
@RequestMapping("/api/search")

public class SearchController {
    
    private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
    
    @Autowired(required = false)
    private WebSearchService webSearchService;
    
    @Autowired
    private AIEnhancementService aiEnhancementService;
    
    /**
     * 执行网络搜索
     */
    @GetMapping("/web")
    public ResponseEntity<Map<String, Object>> webSearch(
            @RequestParam String query,
            @RequestParam(defaultValue = "5") int maxResults) {

        
        logger.info("收到网络搜索请求：{}", query);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (webSearchService == null) {
                response.put("success", false);
                response.put("message", "网络搜索服务未配置");
                return ResponseEntity.ok(response);
            }
            
            List<SearchResult> results = webSearchService.search(query, maxResults);
            
            response.put("success", true);
            response.put("query", query);
            response.put("results", results);
            response.put("count", results.size());
            
            logger.info("网络搜索完成，返回{}条结果", results.size());
            
        } catch (Exception e) {
            logger.error("网络搜索失败", e);
            response.put("success", false);
            response.put("message", "搜索失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取增强上下文
     */
    @GetMapping("/context")

    public ResponseEntity<Map<String, Object>> getEnhancedContext(
            @RequestParam String query,
            @RequestParam(defaultValue = "5") int maxResults) {
        
        logger.info("收到增强上下文请求：{}", query);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<String> contexts = aiEnhancementService.getEnhancedContext(query, maxResults);
            
            response.put("success", true);
            response.put("query", query);
            response.put("contexts", contexts);
            response.put("count", contexts.size());
            
            logger.info("增强上下文获取完成，返回{}条结果", contexts.size());
            
        } catch (Exception e) {
            logger.error("获取增强上下文失败", e);
            response.put("success", false);
            response.put("message", "获取上下文失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取知识库回答
     */
    @PostMapping("/answer")

    public ResponseEntity<Map<String, Object>> getKnowledgeAnswer(
            @RequestBody Map<String, String> request) {
        
        String question = request.get("question");
        logger.info("收到知识库回答请求：{}", question);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (question == null || question.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "问题不能为空");
                return ResponseEntity.ok(response);
            }
            
            String answer = aiEnhancementService.getKnowledgeAnswer(question.trim());
            
            response.put("success", true);
            response.put("question", question);
            response.put("answer", answer);
            
            logger.info("知识库回答完成");
            
        } catch (Exception e) {
            logger.error("获取知识库回答失败", e);
            response.put("success", false);
            response.put("message", "获取回答失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 检查搜索功能状态
     */
    @GetMapping("/status")

    public ResponseEntity<Map<String, Object>> getSearchStatus() {
        
        Map<String, Object> response = new HashMap<>();
        
        response.put("webSearchEnabled", webSearchService != null);
        response.put("aiEnhancementEnabled", aiEnhancementService != null);
        
        if (webSearchService != null) {
            response.put("webSearchService", webSearchService.getClass().getSimpleName());
        }
        
        logger.info("搜索功能状态检查完成");
        
        return ResponseEntity.ok(response);
    }
}